import { InitArguments } from "maishu-chitu-admin/static";
import { ADMIN_APP, loadLess, stationPath } from "./common";
import { LocalService } from "./services/local-service";
import { Component } from "maishu-jueying";
import { contextName } from "json!websiteConfig";
import { ComponentLoader } from "controls/component-loader";

export default async function (args: InitArguments) {

    window[ADMIN_APP] = args.app;

    let localService = args.app.createService(LocalService);
    let files = await localService.clientFiles();

    args.app.pageCreated.add((sender, page) => {
        let className = page.name.split("/").filter(o => o != "").join("-");
        page.element.className = `admin-page ${className}`;

        let lessFilePath: string;
        if (page.name.indexOf(":")) {
            let arr = page.name.split(":");
            lessFilePath = `modules/${arr[1]}.less`;
        }
        else {
            lessFilePath = `modules/${page.name}.less`;
        }
        let pageLessFiles = files.filter(o => o.startsWith("modules") && o.endsWith(".less"));
        if (pageLessFiles.indexOf(lessFilePath) >= 0) {
            loadLess(lessFilePath);
        }
    })

    requirejs({ context: contextName }, ['less!site']);
    requirejs({ context: contextName }, ['qrcode', 'clipboard'], function (qrcode, clipboard) {
        window['QRCode'] = qrcode || window['QRCode'];
        window['ClipboardJS'] = clipboard || window['ClipboardJS']
    })
}

//=============================================================
// 为减少后期组件加载的时间，同时为了不影响当前加载，延时加载所有组件
setTimeout(() => {
    ComponentLoader.loadAllComponents();
}, 1000 * 60);
//=============================================================

async function loadEditors(localService: LocalService) {
    let files = await localService.clientFiles();
    let editorFiles = files.filter(o => o.startsWith("components") && o.endsWith(".js") && o.indexOf("editor") >= 0);
    editorFiles.forEach(path => requirejs({ context: contextName }, [path]));
}

async function loadLessFiles(localService: LocalService) {
    let files = await localService.clientFiles();
    let editorLessFiles = files.filter(o => o.startsWith("components") && o.endsWith("editor.less"));
    editorLessFiles.forEach(path => {
        loadLess(path);
    })
}

